package com.ewili.x.common.config;

import com.ewili.framework.thread.VisiableThreadPoolTaskExecutor;
import com.ewili.x.common.config.properties.TaskThreadPoolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 注意：该线程池被所有的异步任务共享，而不属于某一个异步任务
 * 描述：配置异步任务的线程池
 * 创建时间：2017年5月22日 上午10:20:56
 *
 * @author wonder
 * @version 1.2.0
 */
@Configuration
public class AsyncTaskExecutePool implements AsyncConfigurer {

    @Resource
    private TaskThreadPoolConfig config;

    @Bean //@Bean("myTaskAsyncPool") bean的名称，默认为首字母小写的方法名
    public AsyncTaskExecutor myTaskAsyncPool() {
        VisiableThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        //是否允许核心线程超时
        executor.setAllowCoreThreadTimeOut(config.isAllowCoreThreadTimeOut());
        //核心线程数，线程池活跃的线程数
        executor.setCorePoolSize(config.getCorePoolSize());
        //线程池最大活跃的线程数
        executor.setMaxPoolSize(config.getMaxPoolSize());
        //线程队列大小
        executor.setQueueCapacity(config.getQueueCapacity());
        //线程超时时间
        executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
        executor.setWaitForTasksToCompleteOnShutdown(config.isWaitForTasksToCompleteOnShutdown());
        executor.setThreadNamePrefix(config.getThreadNamePrefix());

        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
